package elephant.servers.consoleserver.command.container;

import java.text.SimpleDateFormat;

import elephant.Container;
import elephant.servers.consoleserver.command.SshdCommand;

/**
 * 
 * @author icecooly
 *
 */
public class ContainerSshdCommand extends SshdCommand{
	//
	ContainerInfo bean;
	//
	public ContainerSshdCommand(){
		super("cc", "show container info");
		bean=new ContainerInfo(Container.get());
		addOption("i",false,"show container info.",this::showContainerInfo);
		addOption("t",false,"show task info.",this::showTaskInfo);
		addOption("j",false,"show job info.",this::showJobInfo);
		addOption("rt",true,"run task.",this::runTask);
		addOption("rj",true,"run job.",this::runJob);
		addOption("http",false,"show FastHttpClientStat info.",this::showHttpInfo);
	}
	//
	private void showJobInfo(String args){
		String format="%-5s %-10s %-20s %-20s %-20s";
		formatPrintln(format,"#","ID","CRON EXPRESSION","NEXT RUN","LAST RUN");
		int i=1;
		SimpleDateFormat sdf=new SimpleDateFormat("MM/dd HH:mm:ss");
		for(JobInfo j:bean.getJobs()){
			formatPrintln(format, 
					i++,
					j.getId(),
					j.getCronExpression(),
					j.getNextRunTime()==null?"NULL":sdf.format(j.getNextRunTime()),
					j.getLastRunTime()==null?"NULL":sdf.format(j.getLastRunTime()));
		}
	}
	//
	private void runJob(String args){
		if(bean.runJob(args)){
			println("run job:"+args+" success.");
		}else{
			println("run job:"+args+" failure.");	
		}
	}
	//
	//
	private void showTaskInfo(String args){
		String format="%-5s %-60s %-20s %-10s %-20s %-10s %-10s";
		formatPrintln(format,"#","ID","INITDELAY","PERIOD","TIMEUNIT","LASTRUNTIME","RUNTIMES");
		int i=1;
		SimpleDateFormat sdf=new SimpleDateFormat("MM/dd HH:mm:ss");
		for(TaskInfo t:bean.getTasks()){
			formatPrintln(format, 
					i++,
					t.getId(),
					t.getInitialDelay(),
					t.getPeriod(),
					t.getUnit(),
					t.getLastRunTime()==null?"NULL":sdf.format(t.getLastRunTime()),
					t.getRunTimes());
		}
	}
	//
	private void runTask(String id){
		if(bean.runTask(id)){
			println("run task:"+id+" success.");
		}else{
			println("run task:"+id+" failure.");	
		}
	}
	//
	private void showHttpInfo(String args){
		println(bean.dumpFastHttpClientInfo());
	}
	//
	private void showContainerInfo(String args){
		String info=bean.dump();
		println(info);
	}
}
